#include <stdio.h>
#include <pthread.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/time.h>

int sqr(int n){
    sleep(1);
    return n*n;
}

void *sqr_thread(void *arg){
    int *result = malloc(sizeof(int));
    *result = sqr(*(int *)arg);
    return result;
}
int main(int argc, char const *argv[])
{
    pthread_t tids[5];
    int sum[5];
    int sums = 0;
    int nums[5] = {1,2,3,4,5};
    struct timeval start, end;
    gettimeofday(&start,NULL);
    for(int i = 0; i < 5; i++){
        pthread_create(&tids[i], NULL, sqr_thread, &nums[i]);
    }
    for (int i = 0; i < 5; i++)
    {
        void *tmp;
        pthread_join(tids[i],&tmp);
        sum[i] = *(int *)tmp;
    }
    for (int i = 0; i < 5; i++)
    {
        sums += sum[i];
    }
    gettimeofday(&end,NULL);
    printf("time = %ld\n",end.tv_sec-start.tv_sec);
    printf("sum = %d\n",sums);
    return 0;
}
